<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class StudyStudentClass extends Model
{
    use SoftDelete;

    protected $deleteTime = false;

    // 获取列表
    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');
        $admin = session('admin');
        if ($admin['school_id'] > 0) {
            $where[] = ['school_id', '=', $admin['school_id']];
        }
        //按班级名称查找
        if ($class_name = input("class_name")) {
            $where[] = ["class_name", "like", "%" . $class_name . "%"];
        }
        $list = self::order('id', 'desc')->where($where)->paginate($limit);
        $data = $list->items();
        foreach ($data as $k => $v) {
            $data[$k]['count'] = StudyStudentList::where('class_id', $v['id'])->count();
        }
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    public function getChild()
    {
        return $this->hasMany(StudyStudentList::class, 'id', 'class_id');
    }

    public static function getStudentList()
    {
        $class_id = input('param.class_id');
        $type = input('param.type',1);
        $where = [];
        if ($type == 2){
            //查询这个班级的所有学生
            $stuId = StudyStudentList::where('class_id',$class_id)->column('id');

            //查询今日打卡的学生
            $punchStu = Db::table('bl_student_attendance')
                ->whereDay('create_time')
                ->whereIn('student_id',$stuId)
                ->column('student_id');


            $ids = array_diff($stuId,$punchStu);
            $ids && $where[] = ['id','in',$ids];
        }
        $limit = input('get.limit');
        $list = StudyStudentList::with([
            'get_class' => function($a) {
                $a->field('id,class_name');
            }
        ])->order('id', 'desc')
            ->where($where)
            ->where(['class_id' => $class_id])
            ->paginate($limit);
        $data = $list->items();
        foreach ($data as $k => $v) {
            // 判断请假
            if (StudyStudentLeave::where('student_id', $v['id'])
                ->where('start_time', '<', time())
                ->where('end_time', '>=', time())
                ->find()) {
                $data[$k]['user_type'] = '请假';
            } else{
                // 判断是否签到
                if (StudentActionAttendance::where('student_id', $v['id'])
                ->where('attendance_type', '到校')->whereTime('add_time', 'today')->find()) {
                    $data[$k]['user_type'] = '签到';
                } else {
                    $data[$k]['user_type'] = '未签到';
                }
            }
        }
        return ['code' => 0, 'data' => $data, 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }
}
